<?php
//------- logistic wxapp -------
namespace app\logi\model;

use app\admin\model\RouteModel;
use think\Model;
use think\Db;

class LogiPostModel extends Model {

    protected $type = [
        'more' => 'array',
    ];

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    /**
     * 关联 user表
     * @return $this
     */
    public function user() {
        return $this->belongsTo('UserModel', 'user_id')->setEagerlyType(1);
    }

    /**
     * 关联分类表
     */
    public function categories() {
        return $this->belongsToMany('LogiCategoryModel', 'logi_category_post', 'category_id', 'post_id');
    }

    /**
     * published_time 自动完成
     * @param $value
     * @return false|int
     */
    public function setPublishedTimeAttr($value) {
        return strtotime($value);
    }

    /**
     * 后台管理添加订单
     * @param array $data 订单数据
     * @param array|string $categories 订单分类 id
     * @return $this
     */
    public function adminAddLogi($data, $categories) {
        $data['author'] = cmf_get_current_admin_id();

        $this->allowField(true)->data($data, true)->isUpdate(false)->save();

        if (!empty($categories)) {
            if (is_string($categories)) {
                $categories = explode(',', $categories);
            }

            $this->categories()->save($categories);
        }

        

        return $this;

    }

    /**
     * 后台管理编辑订单
     * @param array $data 订单数据
     * @param array|string $categories 订单分类 id
     * @return $this
     */
    public function adminEditLogi($data, $categories) {
        $this->allowField(true)->isUpdate(true)->data($data, true)->save();

        if (!empty($categories)) {
            if (is_string($categories)) {
                $categories = explode(',', $categories);
            }

            $oldCategoryIds        = $this->categories()->column('category_id');
            $sameCategoryIds       = array_intersect($categories, $oldCategoryIds);
            $needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
            $newCategoryIds        = array_diff($categories, $sameCategoryIds);

            if (!empty($needDeleteCategoryIds)) {
                $this->categories()->detach($needDeleteCategoryIds);
            }

            if (!empty($newCategoryIds)) {
                $this->categories()->attach(array_values($newCategoryIds));
            }
        }

        return $this;

    }

}
